package com.jinsp.webviewservice.command;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;

import com.jinsp.webviewservice.IClientCallback;
import com.jinsp.webviewservice.IWebViewMainService;
import com.jinsp.webviewservice.webview.CustomWebView;
import com.jinsp.webviewservice.webview.WebViewMainService;

/**
 * Created by luoshuai on 12/31/21
 * <p>
 * 命令分发器
 */
public class CommandDispatcher extends IClientCallback.Stub {

    private static final String TAG = CommandDispatcher.class.getCanonicalName();
    private static volatile CommandDispatcher INSTANCE;
    private IWebViewMainService webViewMainService;
    private boolean isConnected;
    private CustomWebView customWebView;

    private CommandDispatcher() {
    }

    public static CommandDispatcher getInstance() {
        if (INSTANCE == null) {
            synchronized (CommandDispatcher.class) {
                if (INSTANCE == null) {
                    INSTANCE = new CommandDispatcher();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 连接主进程服务
     *
     * @param context 上下文
     */
    public void connectService(Context context) {
        if (!isConnected) {
            context.bindService(new Intent(context, WebViewMainService.class), serviceConnection,
                    Context.BIND_AUTO_CREATE);
        }
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "连接主进程服务成功");
            isConnected = true;
            webViewMainService = IWebViewMainService.Stub.asInterface(service);
            if (webViewMainService != null) {
                try {
                    webViewMainService.registerClientCallback(CommandDispatcher.this);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(TAG, "远程服务断开连接");
            isConnected = false;
        }
    };

    /**
     * 处理HTML的命令
     *
     * @param commandName   命令名
     * @param jsonData      HTML数据
     * @param customWebView WebView对象
     */
    public void executeCommand(String commandName, String jsonData, CustomWebView customWebView) {
        if (!TextUtils.isEmpty(commandName) && !TextUtils.isEmpty(jsonData) && webViewMainService != null) {
            try {
                this.customWebView = customWebView;
                //回调主进程内处理
                webViewMainService.handleWebCommand(commandName, jsonData);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭服务连接
     */
    public void disconnect(Context context) {
        if (webViewMainService != null) {
            try {
                isConnected = false;
                webViewMainService.unregisterClientCallback(this);
                context.unbindService(serviceConnection);
                webViewMainService = null;
                serviceConnection = null;
                customWebView = null;
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void sendMainProcessData(String jsCode) throws RemoteException {
        //接收Android数据返回给HTML
        if (customWebView != null) {
            customWebView.sendDataFromAndroid(jsCode);
        }
    }
}
